/**
 * 关注关系路由处理模块
 * @author HalRui
 * @version 1.0.0
 * @description 处理用户关注、取关、关注列表等相关API路由
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const followsAPI = require('../../libs/follows-api');
const STATUS_CODES = require('../../utils/status-codes');

/**
 * @route POST /follows/follow
 * @description 关注用户
 * @body {number} followerId - 关注者用户ID
 * @body {number} followingId - 被关注者用户ID
 */
router.post('/follow', async (req, res) => {
    try {
        const { followerId, followingId } = req.fields;

        // 参数验证
        if (!followerId || !followingId) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "关注者ID和被关注者ID不能为空"
            });
        }

        // 类型转换
        const followerIdNum = parseInt(followerId);
        const followingIdNum = parseInt(followingId);

        if (isNaN(followerIdNum) || isNaN(followingIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID必须为数字"
            });
        }

        const result = await followsAPI.followUser(followerIdNum, followingIdNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "关注成功",
            data: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "关注失败：" + error.message
        });
    }
});

/**
 * @route POST /follows/unfollow
 * @description 取消关注用户
 * @body {number} followerId - 关注者用户ID
 * @body {number} followingId - 被关注者用户ID
 */
router.post('/unfollow', async (req, res) => {
    try {
        const { followerId, followingId } = req.fields;

        // 参数验证
        if (!followerId || !followingId) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "关注者ID和被关注者ID不能为空"
            });
        }

        // 类型转换
        const followerIdNum = parseInt(followerId);
        const followingIdNum = parseInt(followingId);

        if (isNaN(followerIdNum) || isNaN(followingIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID必须为数字"
            });
        }

        const result = await followsAPI.unfollowUser(followerIdNum, followingIdNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "取消关注失败：" + error.message
        });
    }
});

/**
 * @route GET /follows/status/:followerId/:followingId
 * @description 检查关注状态
 * @param {number} followerId - 关注者用户ID
 * @param {number} followingId - 被关注者用户ID
 */
router.get('/status/:followerId/:followingId', async (req, res) => {
    try {
        const { followerId, followingId } = req.params;

        // 类型转换
        const followerIdNum = parseInt(followerId);
        const followingIdNum = parseInt(followingId);

        if (isNaN(followerIdNum) || isNaN(followingIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID必须为数字"
            });
        }

        const result = await followsAPI.checkFollowStatus(followerIdNum, followingIdNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取关注状态成功",
            data: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取关注状态失败：" + error.message
        });
    }
});

/**
 * @route GET /follows/following/:userId
 * @description 获取关注列表（我关注的人）
 * @param {number} userId - 用户ID
 * @query {number} page - 页码，默认1
 * @query {number} limit - 每页数量，默认20
 */
router.get('/following/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20 } = req.query;

        // 类型转换
        const userIdNum = parseInt(userId);
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);

        if (isNaN(userIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID必须为数字"
            });
        }

        const result = await followsAPI.getFollowingList(userIdNum, pageNum, limitNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取关注列表成功",
            data: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取关注列表失败：" + error.message
        });
    }
});

/**
 * @route GET /follows/followers/:userId
 * @description 获取粉丝列表（关注我的人）
 * @param {number} userId - 用户ID
 * @query {number} page - 页码，默认1
 * @query {number} limit - 每页数量，默认20
 */
router.get('/followers/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20 } = req.query;

        // 类型转换
        const userIdNum = parseInt(userId);
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);

        if (isNaN(userIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID必须为数字"
            });
        }

        const result = await followsAPI.getFollowersList(userIdNum, pageNum, limitNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取粉丝列表成功",
            data: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取粉丝列表失败：" + error.message
        });
    }
});

/**
 * @route GET /follows/stats/:userId
 * @description 获取用户关注统计
 * @param {number} userId - 用户ID
 */
router.get('/stats/:userId', async (req, res) => {
    try {
        const { userId } = req.params;

        // 类型转换
        const userIdNum = parseInt(userId);

        if (isNaN(userIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID必须为数字"
            });
        }

        const result = await followsAPI.getFollowStats(userIdNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取关注统计成功",
            data: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取关注统计失败：" + error.message
        });
    }
});

/**
 * @route POST /follows/batch-check
 * @description 批量检查关注状态
 * @body {number} followerId - 关注者用户ID
 * @body {Array} followingIds - 被关注者用户ID数组
 */
router.post('/batch-check', async (req, res) => {
    try {
        const { followerId, followingIds } = req.fields;

        // 参数验证
        if (!followerId || !followingIds) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "关注者ID和被关注者ID列表不能为空"
            });
        }

        // 类型转换
        const followerIdNum = parseInt(followerId);
        let followingIdsArray;

        try {
            followingIdsArray = Array.isArray(followingIds) ? followingIds : JSON.parse(followingIds);
        } catch (e) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "被关注者ID列表格式错误"
            });
        }

        if (isNaN(followerIdNum) || !Array.isArray(followingIdsArray)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "参数格式错误"
            });
        }

        const followingIdsNum = followingIdsArray.map(id => parseInt(id)).filter(id => !isNaN(id));

        const result = await followsAPI.batchCheckFollowStatus(followerIdNum, followingIdsNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "批量检查关注状态成功",
            data: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "批量检查关注状态失败：" + error.message
        });
    }
});

/**
 * @route GET /follows/mutual/:userId
 * @description 获取互相关注的用户列表
 * @param {number} userId - 用户ID
 * @query {number} page - 页码，默认1
 * @query {number} limit - 每页数量，默认20
 */
router.get('/mutual/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20 } = req.query;

        // 类型转换
        const userIdNum = parseInt(userId);
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);

        if (isNaN(userIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID必须为数字"
            });
        }

        const result = await followsAPI.getMutualFollows(userIdNum, pageNum, limitNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取互相关注列表成功",
            data: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取互相关注列表失败：" + error.message
        });
    }
});

module.exports = router;